import { Model, DataTypes, Op } from 'sequelize';
import Enumerable from 'linq';
import SequelizeClient from '../sequelizeclient';
let sequelize = SequelizeClient.getInstance();
import SubEvent, { SubjectSummary } from './SubjectSummary';
import VouEvent, { Voucher } from './Voucher';
import { VoucherDetail } from './VoucherDetail';
import common from '../common';

//科目
export class Subject extends Model {}

const subjectInit = () => {
  console.log('subject table init');
  Subject.init(
    {
      subjectName: DataTypes.STRING, //科目名称
      subjectCode: DataTypes.STRING, //科目code
      subjectHelpCode: DataTypes.STRING, //帮助代码
      subjectDirection: DataTypes.INTEGER, //借贷方向  0  借   1  贷
      status: DataTypes.INTEGER, //状态   1   有效   0  无效
      type: DataTypes.INTEGER, //类型  1 资产  2 负债  3  权益  4  成本   5  损益
      guid: DataTypes.STRING, //主键key
      parentCode: DataTypes.STRING, //父级code
    },
    { sequelize, modelName: 'subject' },
  );
  SubEvent.init();
  VouEvent.init();
  Subject.hasMany(SubjectSummary, {
    foreignKey: 'subjectCode',
    sourceKey: 'subjectCode',
  });
  SubjectSummary.belongsTo(Subject, {
    foreignKey: 'subjectCode',
    sourceKey: 'subjectCode',
  });

  Subject.hasMany(VoucherDetail, {
    foreignKey: 'subjectCode',
    sourceKey: 'subjectCode',
  });

  VoucherDetail.belongsTo(Subject, {
    foreignKey: 'subjectCode',
    sourceKey: 'subjectCode',
  });
};
const subjectInsert = async subject => {
  let one = await Subject.count({
    raw: true,
    where: { subjectCode: subject.subjectCode },
  });
  if (one === 0) {
    await Subject.create(subject);
    return { success: true, message: '保存成功！' };
  } else {
    return { success: false, message: '已存在对应Code的科目，保存失败！' };
  }
};

const getAllSubject = async type => {
  let baseWhere = {};
  if (type) {
    baseWhere = { type: type };
  }
  //获取第一层数据
  let one = await Subject.findAll({
    include: SubjectSummary,
    where: { ...baseWhere, parentCode: { [Op.or]: ['', null] } },
  });
  let oneData = common.JsonParse(one);
  const subjectCodes = Enumerable.from(oneData)
    .select(d => {
      return d.subjectCode;
    })
    .toArray();
  //获取第二层数据
  let two = await Subject.findAll({
    include: [SubjectSummary],
    where: { ...baseWhere, parentCode: { [Op.in]: subjectCodes } },
  });
  let twoData = common.JsonParse(two);
  const twoSubjectCodes = Enumerable.from(twoData)
    .select(d => {
      return d.subjectCode;
    })
    .toArray();
  //获取第三层数据
  let three = await Subject.findAll({
    include: [SubjectSummary],
    where: { ...baseWhere, parentCode: { [Op.in]: twoSubjectCodes } },
  });
  let threeData = common.JsonParse(three);
  //整合数据
  const result = Enumerable.from(oneData)
    .select(value => {
      return {
        ...value,
        children: Enumerable.from(twoData)
          .where(d => {
            return d.parentCode == value.subjectCode;
          })
          .select(d => {
            return {
              ...d,
              children: Enumerable.from(threeData)
                .where(c => {
                  return c.parentCode == d.subjectCode;
                })
                .toArray(),
            };
          })
          .toArray(),
      };
    })
    .toArray();

  return result;
};

const updateStatus = async request => {
  await Subject.update(
    {
      status: request.status,
    },
    {
      where: {
        id: request.id,
      },
    },
  );
  return { success: true, message: '操作完成！' };
};

const subjectSummaryInsert = async subjectSummary => {
  let one = await SubjectSummary.findOne({
    where: { subjectCode: subjectSummary.subjectCode, summaryData: '' },
  });
  if (one === null) {
    await SubjectSummary.create(subjectSummary);
  } else {
    one.earlyStage = subjectSummary.earlyStage;
    one.borrowSummary = subjectSummary.borrowSummary;
    one.loanSummary = subjectSummary.loanSummary;
    await one.save();
  }
  return { success: true, message: '保存成功！' };
};

const getVoucherReportBySubjectCode = async prama => {
  let report = await Subject.findAll({
    include: {
      model: VoucherDetail,
      include: {
        model: Voucher,
        as: 'voucher',
      },
    },
    attributes: [
      'subjectCode',
      'subjectName',
      'subjectDirection',
      [
        sequelize.fn(
          'strftime',
          '%Y%m',
          sequelize.col('voucherDetails->voucher.voucherDate'),
        ),
        'summaryData',
      ],
      [
        sequelize.fn('SUM', sequelize.col('voucherDetails.debtorAmount')),
        'sumDebtorAmount',
      ],
      [
        sequelize.fn('SUM', sequelize.col('voucherDetails.lenderAmount')),
        'sumLenderAmount',
      ],
    ],
    where: { subjectCode: [...prama.subjectCode] },
    group: [
      'subject.subjectCode',
      sequelize.fn(
        'strftime',
        '%Y%m',
        sequelize.col('voucherDetails->voucher.voucherDate'),
      ),
    ],
  });
  const res = common.JsonParse(report);
  return { success: true, message: '操作完成！', data: res };
};

export default {
  subjectInit,
  subjectInsert,
  getAllSubject,
  updateStatus,
  Subject,
  subjectSummaryInsert,
  getVoucherReportBySubjectCode,
};
